﻿/*
   Win32 message sending
   Created by Randall Maas, Wednesday October 13 2009
   Copyright (c) 2009, Randall Maas
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

   Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

   Neither the name of Blackwood Designs, LLC nor the names of its contributors
   may be used to endorse or promote products derived from this software without
   specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
   THE POSSIBILITY OF SUCH DAMAGE.
*/

using System ;
using System . Runtime . InteropServices;


public static partial class Win32
{
   /// <summary>
   /// Port to send most messages/events to
   /// </summary>
   internal static ISendPort CurrentFocusSendPort = new Win32FocusSendPort();
}


/// <summary>
/// An internal class used to sends messages (events) to the currently focused
/// window
/// </summary>
class Win32FocusSendPort : ISendPort
{
   #region Message Wrapper
   /// <summary>
   /// A wrapper structure used to send HID-style events
   /// </summary>
   /// <seealso cref="http://pinvoke.net/default.aspx/Structures.INPUT" />
   /// <seealso cref="http://blogs.msdn.com/oldnewthing/archive/2009/08/13/9867383.aspx" />
   [StructLayout(LayoutKind.Sequential)]
   struct INPUT
   {
      internal INPUTTYPE   type;
      internal INPUT_UNION i;
   }

   // This generates the anonymous union
  [StructLayout(LayoutKind.Explicit)]
  struct INPUT_UNION
  {
      [FieldOffset(0)]
      public MOUSEINPUT mi;
      [FieldOffset(0)]
      public KEYBDINPUT ki;
      [FieldOffset(0)]
      public HARDWAREINPUT hi;
  };


   /// <summary>
   /// The type of structure employed
   /// </summary>
   enum INPUTTYPE : int
   {
      MOUSE    = 0,
      KEYBOARD = 1,
      HARDWARE = 2
   }
   #endregion



   /// <summary>
   /// Retrieves the extra information for the current thread (?)
   /// </summary>
   /// <returns>The Extra Info</returns>
   /// <seealso cref="http://pinvoke.net/default.aspx/user32/GetMessageExtraInfo.html" />
   /// <seealso cref="http://msdn.microsoft.com/en-us/library/ms644937%28VS.85%29.aspx" />
   [DllImport("user32.dll", EntryPoint = "GetMessageExtraInfo", SetLastError = true)]
   static extern IntPtr GetMessageExtraInfo();

   /// <summary>
   /// Retrieves the extra information for the current thread (?)
   /// </summary>
   /// <returns>The Extra Info</returns>
   public IntPtr DefaultExtraInfo()
   {
      return GetMessageExtraInfo();
   }


   #region Sending Message
   /// <summary>
   /// Sends the events to the current focus window.
   /// </summary>
   /// <param name="nInputs">The number of input "events"</param>
   /// <param name="Inputs">An array of events</param>
   /// <param name="cbSize"></param>
   /// <returns>Number of Inputs that were delivered / enqueued</returns>
   /// <remarks>
   /// Use SetFocus() to set the current focus window
   /// </remarks>
   /// <seealso cref="http://pinvoke.net/default.aspx/user32/SendInput.html" />
   /// <seealso cref="http://msdn2.microsoft.com/en-us/library/ms646310.aspx" />
   [DllImport("user32.dll", EntryPoint = "SendInput", SetLastError = true)]
   static extern uint SendInput(uint nInputs, INPUT[] Inputs, int cbSize);

   /// <summary>
   /// Sends the specified keyboard event to the current focus window
   /// </summary>
   /// <param name="Event">Keyboard Event to Send</param>
   /// <returns>True if the message was sent, false if an error sending</returns>
   /// <remarks>
   /// Use SetFocus() to change the current focus window
   /// </remarks>
   public virtual bool Send(KEYBDINPUT Event)
   {
      INPUT[] Events = new INPUT[1];
      Events[0] . type = INPUTTYPE . KEYBOARD;
      Events[0] . i.ki   = Event;

      // Handle Extended key events, properly marking the event
      short Vk = Events[0] . i.ki . wVk;
      if ((Vk >= 33 && Vk <= 46) || (Vk >= 91 && Vk <= 93))
        Events[0] . i.ki . dwFlags |= KEYEVENTF . EXTENDEDKEY;

      // Send the Event
      return SendInput((uint)Events.Length, Events, Marshal.SizeOf(Events[0])) > 0;
   }


   /// <summary>
   /// Sends the specified mouse event to the current focus window
   /// </summary>
   /// <param name="Event">Mouse Event to Send</param>
   /// <returns>True if the message was sent, false if an error sending</returns>
   /// <remarks>
   /// Use SetFocus() to change the current focus window
   /// </remarks>
   public virtual bool Send(MOUSEINPUT Event)
   {
      INPUT[] Events = new INPUT[1];
      Events[0] . type = INPUTTYPE . MOUSE;
      Events[0] . i.mi   = Event;

      // Send the Event
      return SendInput((uint)Events.Length, Events, Marshal.SizeOf(Events[0])) > 0; // executes moves + clicks, etc
   }


   /// <summary>
   /// Sends the specified hardware event to the current focus window
   /// </summary>
   /// <param name="Event">Hardware Event to Send</param>
   /// <returns>True if the message was sent, false if an error sending</returns>
   /// <remarks>
   /// Use SetFocus() to change the current focus window
   /// </remarks>
   public virtual bool Send(HARDWAREINPUT Event)
   {
      INPUT[] Events = new INPUT[1];
      Events[0] . type = INPUTTYPE . HARDWARE;
      Events[0] . i.hi   = Event;

      // Send the Event
      return SendInput((uint)Events.Length, Events, Marshal.SizeOf(Events[0])) > 0;
   }
   #endregion


   /// <summary>
   /// The destination to send the message to
   /// </summary>
   protected virtual IntPtr Target
   {
      get {return Win32 . HWND_TOPMOST;}
   }

   #region Send Message / Event other than keyboard/mouse
   /// <summary>
   /// Send the message, and returns immediately
   /// </summary>
   /// <param name="Wnd">The window (queue) to send the message to</param>
   /// <param name="Msg"></param>
   /// <param name="wParam"></param>
   /// <param name="lParam"></param>
   /// <returns>O on error, otherwise success</returns>
   /// <seealso cref="http://pinvoke.net/default.aspx/user32/PostMessage.html" />
   /// <seealso cref="http://msdn.microsoft.com/en-us/library/ms644944%28VS.85%29.aspx" />
   [DllImport("user32.dll", EntryPoint = "PostMessageA", SetLastError = true)]
   static extern Int32 PostMessage(IntPtr Wnd, WM Msg, IntPtr wParam, IntPtr lParam);

   /// <summary>
   /// Sends a message to a window and waits for a response
   /// </summary>
   /// <param name="Wnd">The window to send the message to</param>
   /// <param name="Msg"></param>
   /// <param name="wParam"></param>
   /// <param name="lParam"></param>
   /// <returns></returns>
   /// <seealso cref="http://pinvoke.net/default.aspx/user32/SendMessage.html" />
   /// <seealso cref="http://msdn.microsoft.com/en-us/library/ms644950%28VS.85%29.aspx" />
   /// <remarks>
   /// Typically you should use PostMessage
   /// </remarks>
   [DllImport("user32.dll")]
   [return: MarshalAs(UnmanagedType.I4)]
   static extern Int32 SendMessage(IntPtr Wnd, WM Msg, IntPtr wParam, IntPtr lParam);


   /// <summary>
   /// Delegage used to receive the call back when a reply has been received
   /// </summary>
   /// <param name="Wnd">The window that responded</param>
   /// <param name="Msg">The message that was sent</param>
   /// <param name="Data"></param>
   /// <param name="Result"></param>
   delegate void SendMessageDelegate(IntPtr Wnd, WM Msg, IntPtr Data, IntPtr Result);


   /// <summary>
   /// Sends a message to a window
   /// </summary>
   /// <param name="Wnd">The window to send the message to</param>
   /// <param name="Msg"></param>
   /// <param name="wParam"></param>
   /// <param name="lParam"></param>
   /// <param name="CallBack"></param>
   /// <param name="dwData"></param>
   /// <returns></returns>
   /// <seealso cref="http://pinvoke.net/default.aspx/user32/SendMessageCallback.html" />
   /// <seealso cref="http://msdn.microsoft.com/en-us/library/ms644951%28VS.85%29.aspx" />
   [DllImport("user32.dll", EntryPoint = "SendMessageCallback", SetLastError=true, CharSet=CharSet.Auto)]
   [return: MarshalAs(UnmanagedType.I4)]
   static extern Int32 SendMessage(IntPtr Wnd, WM Msg, IntPtr wParam,
        IntPtr lParam, SendMessageDelegate CallBack, IntPtr dwData);


   /// <summary>
   /// Sends the specified image 
   /// </summary>
   /// <param name="Msg"></param>
   /// <param name="Param1"></param>
   /// <param name="Param2"></param>
   /// <returns>True if the message was sent, false if an error sending</returns>
   public virtual bool Send(WM Msg, IntPtr Param1, IntPtr Param2)
   {
      return 0 != PostMessage(Target, Msg, Param1, Param2);
   }

   /// <summary>
   /// Sends the specified image 
   /// </summary>
   /// <param name="Msg"></param>
   /// <param name="Param1"></param>
   /// <param name="Param2"></param>
   /// <param name="CC">The callback to receive the response</param>
   /// <returns>True if the message was sent, false if an error sending</returns>
   public virtual bool Send(WM Msg, IntPtr Param1, IntPtr Param2, SendResponse CC)
   {
      return 0 != SendMessage(Target, Msg, Param1, Param2,
       delegate (IntPtr Wnd, WM Msg2, IntPtr Data, IntPtr Result)
       {
          CC (Result);
       }, IntPtr . Zero);
   }
   #endregion

}


